

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta name="referrer" content="no-referrer" />
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/apple-touch-icon.png">
  <link rel="icon" href="/img/fyy.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="fyy">
  <meta name="keywords" content="">
  
    <meta name="description" content="本地缓存 导入依赖 配置redis主机地址 自动注入RedisTemplate 使用RedisTemplate的方法将缓存放到数据库  缓存问题 缓存穿透：缓存和数据库都没有的数据被大量请求，导致数据库压力过大 解决方案：缓存空对象、布隆过滤器   缓存雪崩：缓存在某一时刻大量失效，请求全部转发到数据库，导致数据库压力过大 解决方案：过期时间设置随机部分、设置热点数据永不过期、降级熔断   缓存击">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis缓存">
<meta property="og:url" content="http://example.com/2021/04/06/DB/Redis/%E7%BC%93%E5%AD%98/index.html">
<meta property="og:site_name" content="fyy-coding">
<meta property="og:description" content="本地缓存 导入依赖 配置redis主机地址 自动注入RedisTemplate 使用RedisTemplate的方法将缓存放到数据库  缓存问题 缓存穿透：缓存和数据库都没有的数据被大量请求，导致数据库压力过大 解决方案：缓存空对象、布隆过滤器   缓存雪崩：缓存在某一时刻大量失效，请求全部转发到数据库，导致数据库压力过大 解决方案：过期时间设置随机部分、设置热点数据永不过期、降级熔断   缓存击">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-04-06T04:13:33.000Z">
<meta property="article:modified_time" content="2024-03-18T12:05:10.899Z">
<meta property="article:author" content="fyy">
<meta property="article:tag" content="Redis">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>Redis缓存 - fyy-coding</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"ufph8TbmK43d1JfQxLvss4KY-MdYXbMMI","app_key":"96APiPOtZEiCQlv5h3jjZfbC","server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  

  
    <!-- Google tag (gtag.js) -->
    <script async>
      if (!Fluid.ctx.dnt) {
        Fluid.utils.createScript("https://www.googletagmanager.com/gtag/js?id=", function() {
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '');
        });
      }
    </script>
  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>fyy-coding</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Redis缓存"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2021-04-06 12:13" pubdate>
          2021年4月6日 中午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          1.9k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          16 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">Redis缓存</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="本地缓存"><a href="#本地缓存" class="headerlink" title="本地缓存"></a>本地缓存</h2><ol>
<li>导入依赖</li>
<li>配置redis主机地址</li>
<li>自动注入RedisTemplate</li>
<li>使用RedisTemplate的方法将缓存放到数据库</li>
</ol>
<h2 id="缓存问题"><a href="#缓存问题" class="headerlink" title="缓存问题"></a>缓存问题</h2><ul>
<li>缓存穿透：缓存和数据库都没有的数据被大量请求，导致数据库压力过大<ul>
<li>解决方案：缓存空对象、布隆过滤器</li>
</ul>
</li>
<li>缓存雪崩：缓存在某一时刻大量失效，请求全部转发到数据库，导致数据库压力过大<ul>
<li>解决方案：过期时间设置随机部分、设置热点数据永不过期、降级熔断</li>
</ul>
</li>
<li>缓存击穿：并发的查询同一条  缓存中没有（缓存到期）但数据库中有 的数据，同时查询数据库导致击穿<ul>
<li>解决方案：设置热点数据永不过期、互斥锁</li>
<li>可以选择加锁，竞争到锁后，确认缓存中是否有数据，没有的情况下再查数据库，然后加入缓存，解锁。</li>
</ul>
</li>
</ul>
<blockquote>
<p>雪崩是：不同数据过期</p>
<p>击穿是：某条热点数据过期</p>
</blockquote>
<h2 id="分布式缓存"><a href="#分布式缓存" class="headerlink" title="分布式缓存"></a>分布式缓存</h2><blockquote>
<p>本地缓存的问题所在：每个微服务都要有缓存，然而缓存的数据可能不一致</p>
</blockquote>
<h3 id="分布式锁"><a href="#分布式锁" class="headerlink" title="分布式锁"></a>分布式锁</h3><p>分布式的项目，本地锁只能锁住当前服务，所以需要分布式锁。</p>
<blockquote>
<p>分布式锁的过程：</p>
<ul>
<li>没获得锁 -&gt; 阻塞或者sleep一会   （或者自旋？）</li>
<li>加锁，但解锁之前服务挂掉，没有执行解锁的逻辑，造成死锁<ul>
<li>解决方法：设置过期时间，时间到了自动解锁</li>
</ul>
</li>
<li>业务没有执行完的时候锁过期了，其它线程拿到了锁，本进程执行完之后，将其他进程的锁删了<ul>
<li>解决方法：锁续期（Redisson有看门狗），删锁的时候确认是自己的锁（对锁加上UUID）</li>
</ul>
</li>
<li>确认是自己的锁，但在将要删除的时候锁过期了换了别人的锁，即想要删除的时候锁被掉包了<ul>
<li>解决方法：删除锁的时候必须保证原子性（判断锁和删锁是原子的），使用redis+Lua脚本完成，脚本是原子的。但比较麻烦，所以可以考虑使用现有框架，比如Redisson。</li>
</ul>
</li>
</ul>
</blockquote>
<h3 id="Redisson"><a href="#Redisson" class="headerlink" title="Redisson"></a>Redisson</h3><ol>
<li><p>导入依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs xml">&lt;!- 练习使用，更推荐使用redisson-spring-boot-starter -&gt;<br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.redisson<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>redisson<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.13.4<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>
</li>
<li><p>开启配置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyRedisConfig</span> &#123;<br><br>    <span class="hljs-meta">@Value(&quot;$&#123;ipAddr&#125;&quot;)</span><br>    <span class="hljs-keyword">private</span> String ipAddr;<br><br>    <span class="hljs-comment">// redission通过redissonClient对象使用 // 如果是多个redis集群，可以配置</span><br>    <span class="hljs-meta">@Bean(destroyMethod = &quot;shutdown&quot;)</span><br>    <span class="hljs-keyword">public</span> RedissonClient <span class="hljs-title function_">redisson</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-type">Config</span> <span class="hljs-variable">config</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Config</span>();<br>        <span class="hljs-comment">// 创建单例模式的配置</span><br>        config.useSingleServer().setAddress(<span class="hljs-string">&quot;redis://&quot;</span> + ipAddr + <span class="hljs-string">&quot;:6379&quot;</span>);<br>        <span class="hljs-keyword">return</span> Redisson.create(config);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>


</li>
<li><p>注入RedissonClient</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> RedissonClient redissonClient;<br></code></pre></td></tr></table></figure>


</li>
<li><p>使用方法进行加锁、解锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">RLock</span> <span class="hljs-variable">lock</span> <span class="hljs-operator">=</span> redissonClient.getLock(<span class="hljs-string">&quot;锁名称，尽量保持唯一性，所以可以写的具体一点&quot;</span>)；<br>lock.lock(); <span class="hljs-comment">//阻塞等待，内为死循环</span><br>lock.unlock();	<span class="hljs-comment">//推荐放入到finally。如果解锁之前，程序宕机也没关系，因为Redisson有看门狗</span><br></code></pre></td></tr></table></figure>

<blockquote>
<p>看门狗：在业务执行完之前，不断延长锁的有效期。默认情况下，锁的超时时间是30s，而看门狗会在时间过去三分之一的时候，即剩余20s的时候将锁的有效期延长成为30s。这个期限可以通过Config.lockWatchdoyTimeout来另行修改。</p>
</blockquote>
</li>
<li><p><code>推荐用法</code>：自己指定锁时间，时间长点即可</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs java">lock.lock(<span class="hljs-number">10</span>, TimeUnit.SECONDS);	<span class="hljs-comment">//指定过期时间后，超时自动解锁，看门狗不会延长锁的有效期。</span><br>lock.tryLock(<span class="hljs-number">100</span>, <span class="hljs-number">10</span>, TimeUnit.SECONDS);	<span class="hljs-comment">//尝试加锁，不会阻塞等待。最多等待100秒，10秒后自动解锁</span><br><span class="hljs-comment">//内部逻辑：</span><br><span class="hljs-comment">//如果设置了锁的超时时间，就执行脚本占锁，</span><br><span class="hljs-comment">//如果没设置锁的超时时间，使用开门狗的时间去占锁，然后根据进程id判断线程没结束？就调用看门狗的定时任务，重新给锁设置过期时间。</span><br><span class="hljs-comment">//定时任务的周期为：锁时间 / 3 </span><br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment">*基于Redis的Redisson分布式可重入读写锁RReadWriteLock Java对象实现了java.util.concurrent.locks.ReadWriteLock接口。其中读锁和写锁都继承了RLock接口。</span><br><span class="hljs-comment">分布式可重入读写锁允许同时有多个读锁和一个写锁处于加锁状态。</span><br><span class="hljs-comment">*/</span><br><span class="hljs-type">RReadWriteLock</span> <span class="hljs-variable">rwlock</span> <span class="hljs-operator">=</span> redisson.getReadWriteLock(<span class="hljs-string">&quot;anyRWLock&quot;</span>);<br><span class="hljs-comment">// 最常见的使用方法</span><br>rwlock.readLock().lock();<br><span class="hljs-comment">// 或</span><br>rwlock.writeLock().lock();<br><span class="hljs-comment">// 10秒钟以后自动解锁</span><br><span class="hljs-comment">// 无需调用unlock方法手动解锁</span><br>rwlock.readLock().lock(<span class="hljs-number">10</span>, TimeUnit.SECONDS);<br><span class="hljs-comment">// 或</span><br>rwlock.writeLock().lock(<span class="hljs-number">10</span>, TimeUnit.SECONDS);<br><br><span class="hljs-comment">// 尝试加锁，最多等待100秒，上锁以后10秒自动解锁</span><br><span class="hljs-type">boolean</span> <span class="hljs-variable">res</span> <span class="hljs-operator">=</span> rwlock.readLock().tryLock(<span class="hljs-number">100</span>, <span class="hljs-number">10</span>, TimeUnit.SECONDS);<br><span class="hljs-comment">// 或</span><br><span class="hljs-type">boolean</span> <span class="hljs-variable">res</span> <span class="hljs-operator">=</span> rwlock.writeLock().tryLock(<span class="hljs-number">100</span>, <span class="hljs-number">10</span>, TimeUnit.SECONDS);<br></code></pre></td></tr></table></figure></li>
</ol>
<h3 id="分布式信号量Semaphore"><a href="#分布式信号量Semaphore" class="headerlink" title="分布式信号量Semaphore"></a>分布式信号量Semaphore</h3><blockquote>
<p>RLock对象完全符合Java的Lock规范，即只有拥有锁的进程才能解锁，如果其他进程尝试解锁会抛出IllegalMonitorStateException的异常。如果需要其他进程也能解锁，可以使用分布式信号量Semaphore。</p>
</blockquote>
<blockquote>
<p>信号量为存储在redis中的一个数字，当这个数字大于0时，即可以调用<code>acquire()</code>方法减少数量，也可以调用<code>release()</code>方法增加数量，但是当调用<code>release()</code>之后小于0的话方法就会阻塞，直到数字大于0</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">RSemaphore</span> <span class="hljs-variable">semaphore</span> <span class="hljs-operator">=</span> redisson.getSemaphore(<span class="hljs-string">&quot;semaphore&quot;</span>);<br>semaphore.acquire();<br><span class="hljs-comment">//或</span><br>semaphore.acquireAsync();<br>semaphore.acquire(<span class="hljs-number">23</span>);<br>semaphore.tryAcquire();<br><span class="hljs-comment">//或</span><br>semaphore.tryAcquireAsync();<br>semaphore.tryAcquire(<span class="hljs-number">23</span>, TimeUnit.SECONDS);<br><span class="hljs-comment">//或</span><br>semaphore.tryAcquireAsync(<span class="hljs-number">23</span>, TimeUnit.SECONDS);<br>semaphore.release(<span class="hljs-number">10</span>);<br>semaphore.release();<br><span class="hljs-comment">//或</span><br>semaphore.releaseAsync();<br></code></pre></td></tr></table></figure>



<h3 id="闭锁（CountDownLatch）"><a href="#闭锁（CountDownLatch）" class="headerlink" title="闭锁（CountDownLatch）"></a>闭锁（CountDownLatch）</h3><blockquote>
<p>基于Redisson的Redisson分布式闭锁CountDownLatch，Java对象<code>RCountDownLatch</code>采用了与<code>java.util.concurrent.CountDownLatch</code>相似的接口和用法。</p>
</blockquote>
<blockquote>
<p>只有在某个方法调用了n次之后，另一个方法才能执行。比如商品被卖了100次，调用卖完了这个方法。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">lockDoor</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-type">RCountDownLatch</span> <span class="hljs-variable">latch</span> <span class="hljs-operator">=</span> redisson.getCountDownLatch(<span class="hljs-string">&quot;anyCountDownLatch&quot;</span>);<br>    latch.trySetCount(<span class="hljs-number">10</span>);<br>    latch.await();<br>&#125;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">gogo</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-type">RCountDownLatch</span> <span class="hljs-variable">latch</span> <span class="hljs-operator">=</span> redisson.getCountDownLatch(<span class="hljs-string">&quot;anyCountDownLatch&quot;</span>);<br>    latch.countDown();		<span class="hljs-comment">//只有lockDoor被调用了10次，这个gogo方法才能执行完</span><br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="缓存和数据库一致性问题"><a href="#缓存和数据库一致性问题" class="headerlink" title="缓存和数据库一致性问题"></a>缓存和数据库一致性问题</h3><ul>
<li>双写模式：写数据库后，写缓存<ul>
<li>问题：并发时，2写进入，写完DB后都写缓存，1写完库，2写完库，2写缓存，1写缓存，有暂时的脏数据</li>
</ul>
</li>
<li>失效模式：写完数据库后，删缓存<ul>
<li>问题：1写完删完，2正在写，此时3开始读，只能读到1，而3读到1之后，2把缓存删了，3把1更新到缓存</li>
<li>解决：缓存设置过期时间，定期更新</li>
<li>解决：写数据写时，加分布式的读写锁。</li>
</ul>
</li>
</ul>
<blockquote>
<p>解决方案：</p>
<ul>
<li>如果是用户纬度数据（订单数据、用户数据），这种并发几率非常小，不用考虑这个问题，缓存数据加上过期时间，每隔一段时间触发读的主动更新即可</li>
<li>如果是菜单，商品介绍等基础数据，也可以去使用canal订阅binlog的方式（数据更新后canal得到日志的消息去更新缓存）<br>缓存数据+过期时间也足够解决大部分业务对于缓存的要求。</li>
<li>通过加锁保证并发读写，写写的时候按顺序排好队。读读无所谓。所以适合使用读写锁。（业务不关心脏数据，允许临时脏数据可忽略）</li>
</ul>
<p>总结：我们<code>能放入缓存的数据本就不应该是实时性、一致性要求超高的</code>。所以缓存数据的时候加上过期时间，保证每天拿到当前最新数据即可。我们<code>不应该过度设计，增加系统的复杂性</code>。遇到<code>实时性、一致性要求高的数据，就应该查数据库</code>，即使慢点。</p>
</blockquote>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Redis/" class="category-chain-item">Redis</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Redis/" class="print-no-link">#Redis</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Redis缓存</div>
      <div>http://example.com/2021/04/06/DB/Redis/缓存/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>fyy</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2021年4月6日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/04/06/DB/Redis/9.%20Redis%E7%94%9F%E4%BA%A7%E9%97%AE%E9%A2%98%E2%98%85%E2%98%85%E2%98%85/" title="Redis生产问题">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Redis生产问题</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/04/06/JUC/%E5%B8%B8%E8%A7%81%E5%90%8C%E6%AD%A5%E5%B7%A5%E5%85%B7%E7%B1%BB/CountDownLatch/" title="CountDownLatch">
                        <span class="hidden-mobile">CountDownLatch</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"ufph8TbmK43d1JfQxLvss4KY-MdYXbMMI","appKey":"96APiPOtZEiCQlv5h3jjZfbC","path":"window.location.pathname","placeholder":null,"avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量
        <span id="leancloud-site-pv"></span>
        次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数
        <span id="leancloud-site-uv"></span>
        人
      </span>
    
    

  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/js/leancloud.js" ></script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
